package edu.vsu.amm.chaos.ui;

import edu.vsu.amm.chaos.api.Parameters;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * User: Илья
 * Date: 10.11.13
 * Time: 16:04
 */
public class ParametersController {

	@FXML
	private TextField valueA;
	@FXML
	private TextField valueB;
	@FXML
	private TextField valueX0;
	@FXML
	private TextField valueY0;
	@FXML
	private TextField iterations;

	private TextField current;

	@FXML
	public void initialize() {
		valueA.setText("1.4");
		valueB.setText("0.3");
		valueX0.setText("0");
		valueY0.setText("0");
		iterations.setText("0.1");
	}

	@FXML
	private void build() {
		Parameters params = readParameters();
		if (params == null) {
			return;
		}

		hide();
		GraphicsController.open(params);
	}

	private Parameters readParameters() {
		Parameters params = new Parameters();

		try {
			params.setA(readDouble(valueA));
			params.setB(readDouble(valueB));
			params.setX0(readDouble(valueX0));
			params.setY0(readDouble(valueY0));
			params.setIterationsThousands(readDouble(iterations));
		} catch (NumberFormatException e) {
			focusAndSelect(current);
			return null;
		}

		if (params.getIterations() <= 0) {
			focusAndSelect(iterations);
			return null;
		}

		return params;
	}

	private double readDouble(TextField textField) {
		current = textField;
		return Double.parseDouble(textField.getText());
	}

	private void focusAndSelect(TextField textField) {
		textField.requestFocus();
		textField.selectAll();
	}

	private static Stage stage;

	public static void open(Stage stage) {
		if (stage == null) {
			return;
		}

		try {
			Parent root = FXMLLoader.load(ParametersController.class.getResource("Parameters.fxml"));
			Scene scene = new Scene(root, 290, 180);
			stage.setTitle("Отображение Хенона - Параметры");
			stage.setResizable(false);
			stage.setScene(scene);
			stage.show();

			ParametersController.stage = stage;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void show() {
		if (stage == null) {
			return;
		}

		stage.show();
	}

	public static void hide() {
		if (stage == null) {
			return;
		}

		stage.hide();
	}
}
